/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import java.io.Serializable;
import javax.persistence.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import Entity.Pet;
import Entity.Owner;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author microraptor
 */
public class OwnerService implements Serializable{
    private EntityManagerFactory emf = null;
    PetService petService = null;
    
    public OwnerService (EntityManagerFactory emf){
        this.emf = emf;
        this.petService = new PetService(emf);
    }
    
    public EntityManager getEntityManager(){
        return emf.createEntityManager();
    }
    
    public Owner findOwner2(Long id){
        EntityManager em = null;
        Owner owner = null;
        try{
            em = getEntityManager();
            owner = em.find(Owner.class, id);
        }finally{
            if(em != null){
                em.close();
            }
        }
        return owner;
    }
    
    public void crear(Owner owner){
        EntityManager em = null;
        try{
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(owner);
            em.getTransaction().commit();
        }finally{
            if(em != null){
                em.close();
            }
        }
    }
    
    public void edit(Owner owner) throws Exception{
        EntityManager em = null;
        try{
            em = getEntityManager();
            em.getTransaction().begin();
            owner = em.merge(owner);
            em.getTransaction().commit();
        }catch (Exception ex){
            String msg = ex.getLocalizedMessage();
            if (msg == null ||  msg.length() == 0){
                Long id = owner.getId();
                if (findOwner(id) == null){
                    throw new Exception("The pet with id "+id+" no longer exists.");
                }
            }
            throw ex;
        }finally{
            if (em != null){
                em.close();
            }
        }
    }
    
    public void destroy (Long id) throws Exception{
        EntityManager em = null;
        try{
            em=getEntityManager();
            em.getTransaction().begin();
            Owner owner;
            try{
                owner = em.getReference(Owner.class, id);
                owner.getId();
            }catch(EntityNotFoundException ex){
                throw new Exception ("The owner with id "+id+" no longer exists.", ex);
            }
            em.remove(owner);
            em.getTransaction().commit();
        }finally{
            if(em != null){
                em.close();
            }
        }
    }
    
    public List<Owner> findOwnerEntities(){
        return findOwnerEntities(true, -1,-1);
    }
    
    public List<Owner> findOwnerEntities(int maxResults, int firstResult){
        return findOwnerEntities(false, maxResults, firstResult);
    }
    
    private List<Owner> findOwnerEntities(boolean all, int maxResults, int firstResult)    {
        EntityManager em = getEntityManager();
        try{
            CriteriaQuery cq =  em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Owner.class));
            Query q = em.createQuery(cq);
            if(!all){
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            
            for (int i =0;i<q.getResultList().size(); i++){
                Owner owner = (Owner) q.getResultList().get(i);
                long ownerId = owner.getId();
//                Query query = em.createNativeQuery("select appoinments_PersonID from veterinarian_appoinments"
//                        + " where Veterinarian_ID = " + ownerId);
                Query query = em.createNativeQuery("select ID from pet"
                        + " where OWNER_PersonID = " + ownerId);
                owner.setPets(findPets(query));
            }   
            return q.getResultList();
        }finally{
            em.close();
        }
    }
    
    @SuppressWarnings ("empty-statement")
    public Owner findOwner(Long id){
        EntityManager em = getEntityManager();
        try{
            Owner owner = em.find(Owner.class, id);
            long ownerId = owner.getId();
            Query query = em.createNativeQuery("select ID from pet"
                        + " where OWNER_PersonID = " + ownerId);
            owner.setPets(findPets(query));
            return owner;
        }finally{
            em.close();
        }
    }
    
    private List<Pet> findPets(Query query){
        List<Pet> pets = new ArrayList<>();
        for(int i=0; i<query.getResultList().size(); i++){
            Long petId = (Long) query.getResultList().get(i);
            pets.add(petService.findPet(petId));
        }
        return pets;
    }
    
    public int getAppointmentCount(){
        EntityManager em = getEntityManager();
        try{
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Owner> rt = cq.from(Owner.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long)q.getSingleResult()).intValue();
        }finally{
            em.close();
        }
    }
}
